script structure:
Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show(
"What the fack is going on????",
"Important message",
[System.Windows.MessageBoxButton]::OK,
[System.Windows.MessageBoxImage]::Information
)
-ExecutionPolicy Bypass -File "C:\Scripts\morning_note.ps1"
MINI Coupe 1.6 Cooper Euro 6 (s/s) 2dr
New Service & MOT
Model year:
2014 (64)
Fuel type:
Petrol
Mileage:
54,236
Transmission:
Manual
Engine size:
1.6L
Colour:
Red
Live Video Viewings, Delivery & Pay & Collect Services Available, Call To Arrange - Our Post Code Is LE2 6UP - Independent family run business - Buy from a dealer you can trust - All our cars are hand picked direct from main dealers. They are Mileage verified on the National Mileage Register. A Parts & Labour warranty is included on all cars. Credit & Debit cards accepted, for a full up to date stock list click on www.greasleys.co.uk. All our Cars can be viewed in our indoor warehouse, Next MOT due 06/08/2026, Last serviced on 12/08/2025 at 54,236 miles, Red, 4 owners, £4,995
This car comes with
CHILI Pack, 17in Alloy Wheels - Light Conical Spoke, Air Conditioning - Automatic, Seats - Sports Front, Multifunction Controls for Steering Wheel, Interior Surfaces - Piano Black, Colour Line - Carbon Black, Chrome Line Exterior, Interior Light Pack, Rain Sensor and Automatic Headlight Activation, Roof and Mirror Caps - Black, Ray Cloth-Leather - Carbon Black, 15in Alloy Wheels - Light 7-Hole, 3-Spoke Sport Leather Steering Wheel, 3rd Brake Light, ASC+T - Automatic Stability Control and Traction, Air Conditioning - Manual, Airbags - Driver, Airbags - Front Passenger, Airbags - Front Passenger with Deactivation Switch, Airbags - Head and Thorax, Alarm - Thatcham CAT1, Anthracite Headlining, Anti-Lock Braking System - ABS, Aux-In Connection, Basic Bluetooth Function with USB Audio, Brake Force Display, Brake Pad Wear Indicator, CBC - Cornering Brake Control, Car Jack, Central Locking - Activated At 10mph, Central Locking - Remote, Chrome Strip Across Lower Front Apron, Crash Sensor - Fuel Cut-Off, Crash Sensor - Hazard Warning Flashers and Interior Light, Crash Sensor - Unlocking Doors, Cupholders - Two in Front, DAB Tuner, Door Handles - Chrome Plated, Door Mirrors - Electrically Adjustable and Heated, Door Sill Finishers - Metal Look and Model Dependent Lettering, Dynamic Stability Control - DSC, EBD - Electronic Brake-Force Distribution, Electric Windows - Front - One Touch Up and Down, Electronic Power Steering - Speed Related, Embellisher at Bottom Edge of All Windows - Chrome Plated, Gearshift-Selector Lever and Handrake Lever Gaiters in Sensatec, Halogen Lights for Low Beam and High Beam Headlights, Headlight - Beam-Throw Control Electrical with Manual Adjustment, Headlights - Chrome Bezels, Headlights - Follow Me Home, Headrests For All Seats - Manually Adjustable, Heated Front Windscreen Washer Jets, Heated Rear Window with Automatic Deactivation, Hill Assist, Interior Lighting Integrated into Centre Front Headliner Above Interior Mirror, Interior Surface in Fine White Silver and Door Rings in Black, Interior World - Carbon Black, Lashing Eyes in Luggage Compartment, Luggage Compartment - Partition with Large Through-Loading Door, MINI Mobility System, Microfilter, PDC - Park Distance Control - Rear, Passenger Seat Height Adjustable, Radiator Grille - Chrome Plated, Radio BOOST CD, Roof Spoiler Painted in Roof Colour, Seats - Height Adjustable Front, Second Radio Remote Key, Security Locking Wheel Bolts, Shift Point Display, Spoiler - Active Rear (Speed Related), Sport Button, Sport Stripes - Black, Start-Stop Button, Steering Column Height and Length Adjustment, Sun Visors with Integrated Vanity Mirrors on Drivers and Passengers Sides, TPWS - Tyre Pressure Warning System, Tool Kit in Luggage Compartment, White Direction Indicators Lights
VEHICLE SUMMARY
Body style Coupe
Engine size 1598 cc
Fuel type Petrol
Number of doors 2
Number of seats 2
Gearbox type Manual 6Spd
CO2 emissions 127 g/km
Insurance group 18E
Standard manufacturer's warranty (miles) No details available
Standard manufacturer's warranty (years) 3 years
Standard paintwork guarantee 3 years
PERFORMANCE & ECONOMY
Fuel consumption (urban) 40.90 mpg
Fuel consumption (extra urban) 61.40 mpg
Fuel consumption (combined) 52.30 mpg
0 - 60 mph No details available
Top speed 127 mph
Cylinders 4
Valves 16
Engine power 120 bhp
Engine torque 118.00 lbs/ft
DIMENSIONS
Height 1378 mm
Height inclusive of roof rails No details available
Length 3728 mm
Wheelbase 2467 mm
Width 1892 mm
Width including mirrors No details available
Fuel tank capacity 40.00 litres
Minimum kerb weight 1090 kg
INTERIOR/EXTERIOR
Interior features
3-Spoke Sport Leather Steering Wheel
3rd Brake Light
Air Conditioning - Manual
Aux-In Connection
Basic Bluetooth Function with USB Audio
Cupholders - Two in Front
DAB Tuner
Daytime Running Lights - Halogen
Electronic Power Steering - Speed Related
Halogen Lights for Low Beam and High Beam Headlights
Headlight - Beam-Throw Control Electrical with Manual Adjustment
Headlights - Follow Me Home
Lashing Eyes in Luggage Compartment
Luggage Compartment - Partition with Large Through-Loading Door
Radio BOOST CD
Seats - Height Adjustable Front
Start-Stop Button
Steering Column Height and Length Adjustment
Tool Kit in Luggage Compartment
Exterior features
15in Alloy Wheels - Light 7-Hole
Door Handles - Chrome Plated
Door Mirrors - Electrically Adjustable and Heated
Electric Windows - Front - One Touch Up and Down
Heated Front Windscreen Washer Jets
MINI Mobility System
Radiator Grille - Chrome Plated
Security Locking Wheel Bolts
Spoiler - Active Rear (Speed Related)
SAFETY
ASC+T - Automatic Stability Control and Traction
Airbags - Driver
Airbags - Front Passenger
Airbags - Front Side
Airbags - Head and Thorax
Alarm - Thatcham CAT1
Anti-Lock Braking System - ABS
Brake Force Display
Brake Pad Wear Indicator
CBC - Cornering Brake Control
Central Locking - Activated At 10mph
Central Locking - Remote
Crash Sensor - Fuel Cut-Off
Crash Sensor - Hazard Warning Flashers and Interior Light
Crash Sensor - Unlocking Doors
Dynamic Stability Control - DSC
EBD - Electronic Brake-Force Distribution
Hill Assist
PDC - Park Distance Control - Rear
Second Radio Remote Key
Shift Point Display
TPWS - Tyre Pressure Warning System
V5 slip
Service record
Change ownership
Introduction
In Swift applications, you often need to bundle JSON files for local data or settings.
This guide explains how to locate those files using Bundle URLs, load them as Data, and decode them into your custom Swift ty
We will also cover error handling for decoding issues, handling date formats, and how to encode your types back into JSON.
Finally, we wrap everything in a reusable Bundle extension.
1. Locating Files in the Bundle
The first step is finding the file.
Swift's Bundle API provides the url(forResource:withExtension:) method.
It returns an optional URL pointing to the resource if it exists.
Use a guard statement to safely unwrap it and provide a clear error if the file is missing.
Example:
guard let url = Bundle.main.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
2. Reading Data from URL
Once you have the URL, initialize a Data object from its contents.
Use try? or do/catch to handle IO errors, and use a guard to fatalError if loading fails.
Example:
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
3. Setting Up JSONDecoder
Create a JSONDecoder instance.
If your JSON includes dates in custom format, set the decoder's dateDecodingStrategy with a DateFormatter.
This ensures dates are parsed correctly.
Example:
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "y-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
4. Decoding into Custom Types
Define your Swift types to conform to Codable.
Call decoder.decode(T.self, from: data) inside a do/catch block.
Handle DecodingError cases to provide detailed failure messages for missing keys, type mismatches, unexpected nulls, or inval
Example:
do {
return try decoder.decode(T.self, from: data)
} catch DecodingError.keyNotFound(let key, let ctx) {
fatalError("Missing key \(key): \(ctx.debugDescription)")
} // handle other error cases similarly
5. Encoding Custom Types
To send or save your types back as JSON, create a JSONEncoder, optionally set outputFormatting for readability, and call enco
Write the resulting Data to disk or send it over the network.
Example:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let outData = try encoder.encode(instance)
try outData.write(to: fileURL)
Full Example with extension on Bundle:
extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
// locate the file
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in the bundle!")
}
// read the file into Data type!
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from the bundle!")
}
// creating an instance of json decoder
let decoder = JSONDecoder()
// date formatter to how to decode dates!
let formatter = DateFormatter()
formatter.dateFormat = "y-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
// decode the content of the file
do {
return try decoder.decode(T.self, from: data)
} catch DecodingError.keyNotFound(let key, let context) {
fatalError("Failed to decode \(file) from bundle due to missing key: \(key) - \(context.debugDescription)")
} catch DecodingError.typeMismatch(_ , let context) {
fatalError("Failed to decode \(file) from bundle due to type mismatch - \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
fatalError("Failed to decode the \(file) from bundle due to missing \(type) value - \(context.debugDescription)")
} catch DecodingError.dataCorrupted(_) {
fatalError("Failed to decode \(file) fromt the bundle becuase it appears to be invalid JSON!")
} catch {
fatalError("Failed to decode \(file) from the bundle: \(error.localizedDescription)")
}
}
}
===============================
SwiftData and SwiftUI Summary
===============================
1. SwiftData and Its Core Components
- SwiftData: Apple's modern framework for handling persistent storage in SwiftUI.
- modelContainer: Acts as the "database manager" ensuring data persistence. It sets up the storage environment where data models reside.
- modelContext: Serves as the "workspace" where you track, modify, and commit changes to your data. Changes made in the context are saved back to the modelContainer.
- @Query Macro: Enables automatic fetching of data from SwiftData models. It supports filtering (using predicates) and sorting via key paths.
--------------------------------
2. Understanding Macros in SwiftUI & SwiftData
- Macros (e.g., @Model, @Query):
• Expand into more complex code at compile time.
• They reduce repetitive coding by generating boilerplate logic.
• Example: @Model converts a simple class declaration into a full SwiftData model with persistence logic.
• Example: @Query(filter: #Predicate { $0.age > 25 }) automatically fetches filtered objects.
--------------------------------
3. Predicates & KeyPaths Explained
- Predicates:
• They define filters for querying objects.
• Example: #Predicate { $0.age > 25 } selects objects where the 'age' property is greater than 25.
- KeyPaths:
• They reference specific properties of a model, often used for accessing or sorting data.
• Example: sort: \User.name references the 'name' property of the User model for sorting.
--------------------------------
4. Environment in SwiftUI
- Environment:
• A mechanism in SwiftUI for storing and accessing global/shared values.
• Uses the @Environment property wrapper to allow child views to retrieve these values automatically.
• Eliminates the need to pass values manually through every view in a hierarchy.
- Usage Example:
Parent view injects a value via:
.environment(\.themeColor, .blue)
And child views access it using:
@Environment(\.themeColor) var themeColor
--------------------------------
5. Distinguishing Property Wrappers vs. Macros
- Property Wrappers (e.g., @Environment):
• Work at runtime to modify how a property behaves.
• They retrieve existing values in a dynamic fashion (e.g., fetching a global setting from the environment).
- Macros (e.g., @Model):
• Expand into new code at compile time, generating additional boilerplate automatically.
• They add underlying persistence or automatic reactivity to your models.
Key Differences:
• Property wrappers modify behavior at runtime.
• Macros generate extra code during compilation before the app runs.
Summary:
- SwiftData simplifies data persistence with modelContainer and modelContext.
- Macros like @Model and @Query reduce boilerplate by auto-generating code.
- @Environment simplifies dependency management in SwiftUI.
- KeyPaths (using "\") reference properties, while Predicates (using "#") define filtering conditions.
===========================================
End of SwiftData and SwiftUI Summary
===========================================
What Is Bubble Sort?
Bubble sort works by repeatedly traversing a list and swapping adjacent elements if they are in the wrong order. With each pass through the list, the largest (or smallest, depending on the sorting order) unsorted element “bubbles” up to its correct position—much like bubbles rising to the surface in water.
How Bubble Sort Works
Compare Adjacent Elements:
Start at the beginning of the list and compare each pair of adjacent elements.
Swap if Necessary:
If the left element is greater than the right element (for ascending order), swap them. This ensures that, after one full pass, the largest element moves to the end of the list.
Repeat Passes:
Continue the process for the remaining unsorted portion of the list. With each pass, the unsorted section shrinks as the largest elements settle into their correct positions at the end of the list.
Stop When Sorted:
Optionally, if a pass is completed without any swaps, the list is already sorted and the algorithm can terminate early.
Everyday Analogy
Imagine you have a row of books that you want to arrange from the shortest to the tallest. You start by comparing the first two books and swapping them if the first is taller. Then, you move to the next pair and repeat the process until you reach the end. By the end of the first round, the tallest book will be at the right end. You then repeat the process for the remaining books until the entire row is in order.
Time and Space Complexity
Time Complexity
Best-Case Scenario:
If the list is already sorted, bubble sort can detect this after one full pass without swaps, making the best-case time complexity O(n).
Average and Worst-Case Scenarios:
For a list in random order or in reverse order, bubble sort must perform multiple passes. This results in a time complexity of O(n²), where n is the number of elements in the list.
Space Complexity
Space Complexity:
Bubble sort is an in-place sorting algorithm, meaning it requires only a constant amount of extra memory (O(1)) beyond the input list.
Other Relevant Facts
Simplicity:
Bubble sort is very simple to implement and understand, making it a popular teaching tool.
Stability:
Bubble sort is a stable sort, meaning that two equal elements maintain their relative order after sorting.
Not Suitable for Large Datasets:
Due to its quadratic time complexity in the average and worst cases, bubble sort is inefficient for sorting large lists.
Optimization Potential:
A common optimization is to include a flag that checks whether any swaps occurred in a pass. If no swaps occur, the list is already sorted, and the algorithm can terminate early.
Python Implementation
Below is a Python implementation of bubble sort that includes an optimization to exit early if no swaps are made:
def bubble_sort(lst):
"""
Sorts the list 'lst' in ascending order using the bubble sort algorithm.
Bubble sort works by repeatedly stepping through the list,
comparing adjacent elements and swapping them if they are in the wrong order.
This process is repeated until the list is sorted.
Parameters:
lst (list): The list of elements to sort.
Returns:
None: The list is sorted in place.
"""
n = len(lst)
# Traverse through all elements in the list
for i in range(n):
# Initially, assume no swap has been made in this pass
swapped = False
# Last i elements are already in place
for j in range(0, n - i - 1):
# Compare adjacent elements
if lst[j] > lst[j + 1]:
# Swap if the element found is greater than the next element
lst[j], lst[j + 1] = lst[j + 1], lst[j]
swapped = True
# If no two elements were swapped by inner loop, then break early
if not swapped:
break
# Example usage:
if __name__ == "__main__":
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted list:", unsorted_list)
bubble_sort(unsorted_list)
print("Sorted list:", unsorted_list)
Conclusion
Bubble sort is a simple yet illustrative sorting algorithm that teaches fundamental concepts such as comparisons, swapping, and algorithmic efficiency. While it’s not practical for large datasets due to its O(n²) time complexity, its ease of implementation and understanding makes it a valuable educational tool. The Python implementation above demonstrates these concepts, along with an optimization to stop early when the list is already sorted.
By understanding bubble sort, you'll gain a foundation for grasping more complex sorting algorithms and algorithmic thinking in general.
Imagine you have a word, like “cat.” You want your computer to “understand” what that word represents in a mathematical way—something you can store and use in a program. An embedding is just a method to translate that word (or any object, like an image or sentence) into a sequence of numbers. These numbers capture some important features or meaning about “cat,” so that a computer can recognize similarities and differences between it and other words or objects.
In other words, embeddings help us move from “words in a language” to “points in a mathematical space.” Each word becomes a dot (or point) located somewhere in that space. Similar words (like “cat” and “kitten”) end up being close together, while very different words (like “cat” and “skyscraper”) are placed far apart.
Example
Let’s say we pick 2 numbers to represent each word (so, a 2-dimensional embedding). A simple example might look like this:
“Cat” → (0.2, 0.7)
“Kitten” → (0.3, 0.8)
“Skyscraper” → (8.9, 3.2)
Here, “Cat” and “Kitten” might have closer numbers because they are more similar (both are animals). “Skyscraper” has very different numbers, placing it far away in this 2-dimensional space.
In this article, we will dive deep into the concept of classes in Python, an
integral part of Object-Oriented Programming (OOP). We'll break down a simple
example and explore how Python implements classes under the hood.
What is a Class?
A class in Python is a blueprint for creating objects. It defines the structure and
behavior (attributes and methods) that the objects created from the class will
have. Think of a class as a template, and the objects as the actual "things"
created using this template.
Let's explore this with an example:
class MercedezBenz:
pass
Here, we define a class named MercedezBenz. This class currently doesn't do
anything because it doesn't have any attributes or methods. It's just an empty
blueprint.
Examining the Class in Python:
When we define a class in Python, several things happen in the background.
Let's analyse these using the following code:
if __name__ == "__main__":
print(MercedezBenz)
# Classes are of type type!
print(type(MercedezBenz))
print(MercedezBenz.__bases__)
print(MercedezBenz.__name__)
# Classes are callable!
print(MercedezBenz())
1. Printing the Class Name
When we print the MercedezBenz class, Python tells us that it's a class object:
print(MercedezBenz)
# Output: <class '__main__.MercedezBenz'>
This shows that MercedezBenz is a class defined in the __main__ module (the
main script being executed).
2. Classes are of Type `type`
In Python, everything is an object, including classes themselves. The type of
any class is `type`:
print(type(MercedezBenz))
# Output: <class 'type'>
This means that the `type` class is responsible for creating all other classes,
including user-defined ones like `MercedezBenz`.
3. Base Classes
Every class in Python inherits from a base class. By default, this is the `object`
class:
print(MercedezBenz.__bases__)
# Output: (<class 'object'>,)
The __bases__ attribute shows the tuple of base classes. For MercedezBenz,
the only base class is `object`.
4. Class Name
The __name__ attribute gives the name of the class as a string:
print(MercedezBenz.__name__)
# Output: MercedezBenz
5. Classes are Callable
Classes in Python are callable, which means we can use parentheses `()` to
create an instance (object) of the class:
print(MercedezBenz())
# Output: <__main__.MercedezBenz object at 0x...>
Creating and Comparing Instances
Creating Instances
We can create multiple instances (objects) of a class. Each instance is a
separate object in memory:
obj_1 = MercedezBenz()
obj_2 = MercedezBenz()
print(obj_1)
# Output: <__main__.MercedezBenz object at 0x...>
print(obj_2)
# Output: <__main__.MercedezBenz object at 0x...>
Comparing Instances
Even though obj_1 and obj_2 are both instances of the same class, they are
different objects in memory:
print(obj_1 == obj_2)
# Output: False
print(obj_1 is obj_2)
# Output: False
The `==` operator checks for equality, and `is` checks for identity (i.e., whether
they are the exact same object in memory). Here, they are not the same.
Checking Types
We can use the isinstance function to check if an object is an instance of a
specific class:
print(isinstance(obj_1, MercedezBenz))
# Output: True
print(isinstance(obj_2, MercedezBenz))
# Output: True
Summary
- A class in Python is a blueprint for creating objects.
- Classes are of type `type`, and they are callable.
- Instances created from a class are separate objects, even if they belong to the same class.
- We can use attributes like `__bases__`, `__name__`, and functions like
`isinstance` to inspect and interact with classes and objects.
Understanding the basics of classes and objects is the first step in mastering
Object-Oriented Programming in Python. With this foundation, you can begin to
add attributes, methods, and more complex functionality to your classes.
In this article, we will explore the concept of class attributes, also known as the "state" of a class, in Python. Class attributes are shared by all instances of a class and define common properties that the instances inherit.
What are Class Attributes?
Class attributes are variables that are defined inside a class but outside of any instance methods. These attributes belong to the class itself and are shared across all instances of the class.
Let's take a look at an example:
class MercedezBenz:
colour = 'red'
doors = 4
In this example, MercedezBenz has two class attributes:
colour with a value of 'red'
doors with a value of 4
These attributes are part of the class's state and can be accessed directly from the class or its instances.
Accessing Class Attributes
We can access class attributes using the class name or an instance of the class:
if __name__ == "__main__":
# Accessing the class attributes via the class name
print(MercedezBenz.colour) # Output: red
print(MercedezBenz.doors) # Output: 4
# Accessing the class attributes via an instance
obj_1 = MercedezBenz()
print(obj_1.colour) # Output: red
print(obj_1.doors) # Output: 4
Class Namespace and __dict__
The class attributes are stored in the class's namespace, which can be accessed using the __dict__ attribute:
print(MercedezBenz.__dict__)
Output:
{'__module__': '__main__', 'colour': 'red', 'doors': 4, '__dict__': <attribute '__dict__' of 'MercedezBenz' objects>, '__weakref__': <attribute '__weakref__' of 'MercedezBenz' objects>, '__doc__': None}
This dictionary contains all the class attributes and some additional metadata about the class.
Adding Class Attributes Dynamically
You can add attributes to a class even after its definition. These new attributes will be available to all instances of the class:
MercedezBenz.model = 2025
print(MercedezBenz.model) # Output: 2025
obj_2 = MercedezBenz()
print(obj_2.model) # Output: 2025
Here, the model attribute was added dynamically to the MercedezBenz class. It is now accessible via both the class and its instances.
Shared Nature of Class Attributes
All instances of a class share the same class attributes. If you change the value of a class attribute using the class name, the change will be reflected in all instances:
print(obj_1.colour) # Output: red
print(obj_2.colour) # Output: red
Since colour is a class attribute, both obj_1 and obj_2 inherit its value from the MercedezBenz class.
Summary
Class attributes are variables that belong to the class itself and are shared by all instances of the class.
They are stored in the class namespace, which can be accessed using the __dict__ attribute.
New attributes can be added to a class dynamically, and they will be shared across all instances.
Class attributes are an efficient way to define properties that are common to all objects of a class.
Understanding class attributes is crucial for effectively using and designing classes in Python. They form the foundation for managing shared data in Object-Oriented Programming.